package com.sy.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.sy.dao.AdminDao;
import com.sy.sql.DataBaseConnection;
import com.sy.util.StringUtil;
import com.sy.vo.Admin;

public class AdminDaoImpl implements AdminDao {
//是否登陆成功
	public boolean isLogin(Admin admin)
	{
		boolean flag = false ;

		PreparedStatement pstmt	= null ;
		ResultSet rs			= null ;
		String sql				= null ;
		DataBaseConnection dbc= new DataBaseConnection() ;
		sql = "SELECT * FROM admin WHERE aname=? and apassword= ?" ;
		try
		{			
			pstmt = dbc.getSql(sql);
			pstmt.setString(1,admin.getAname()) ;
			pstmt.setString(2,admin.getApassword()) ;
			
			rs = pstmt.executeQuery() ;
			if(rs.next())
			{
				flag = true ;
			}
			rs.close() ;
			pstmt.close() ;
		}
		catch(Exception e)
		{
			System.out.println(e) ;
		}
		finally
		{
			dbc.close() ;
		}
		return flag ;
	}
//添加管理员
	public int add(String aname,String apassword) {
		int result=0;
		PreparedStatement pstmt	= null ;
		String sql				= null ;
		DataBaseConnection dbc= new DataBaseConnection() ;
		sql = "insert into admin(aname,apassword) values(?,?)";
		try
		{			
			pstmt = dbc.getSql(sql);
			pstmt.setString(1,StringUtil.filterHtml(aname));
			pstmt.setString(2,StringUtil.filterHtml(apassword));
			result = pstmt.executeUpdate();
			pstmt.close() ;
		}
		catch(Exception e)
		{
			System.out.println(e) ;
		}
		finally
		{
			dbc.close() ;
		}
		return result;
	}
//删除管理员
	public void delete(Integer aid) {
		PreparedStatement pstmt	= null ;
		String sql				= null ;
		DataBaseConnection dbc= new DataBaseConnection() ;
		sql = "delete from admin WHERE aid=?";
		try
		{			
			pstmt = dbc.getSql(sql);
			pstmt.setInt(1,aid);
			pstmt.executeUpdate();//这句必须加
			pstmt.close();
		}
		catch(Exception e)
		{
			System.out.println(e) ;
		}
		finally
		{
			dbc.close() ;
		}
	}
//获取管理员列表
	@SuppressWarnings("unchecked")
	public List<Admin> getAdmin() {
List<Admin> adminss=new ArrayList();
		
		PreparedStatement pstmt	= null ;
		String sql				= null ;
		ResultSet rs			= null ;
		DataBaseConnection dbc= new DataBaseConnection() ;
		sql = "select * from admin order by aid desc";
		try
		{			
			pstmt = dbc.getSql(sql);
			rs = pstmt.executeQuery() ;
			while(rs.next())
			{
				Admin admin=new Admin();
				admin.setAid(rs.getInt("aid"));
				admin.setAname(rs.getString("aname"));
				admin.setApassword(rs.getString("apassword"));
				
				adminss.add(admin);
			}
			rs.close() ;
			pstmt.close() ;
		}
		catch(Exception e)
		{
			System.out.println(e) ;
		}
		finally
		{
			dbc.close();
		}
		return adminss;
	}
}
